//
//  AppData.m
//  cutter
//
//  Created by zhouliangfei on 16/5/3.
//  Copyright © 2016年 e360. All rights reserved.
//

#import "AppData.h"

id filterEmpty(id object){
    if (isEmpty(object)) {
        return nil;
    }
    return object;
}
//
//
@implementation AppData
+(void)load{
    NSLog(@"%@",pathForLibrary(@""));
    NSLog(@"%@",pathForResource(@""));
    //
    NSString *base = pathForLibrary(@"~kasa.sqlite");
    if ([[NSFileManager defaultManager] fileExistsAtPath:base] == NO) {
        NSString *clone = pathForResource(@"kasa.sqlite");
        [[NSFileManager defaultManager] copyItemAtPath:clone toPath:base error:nil];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkDidChange:) name:UIDeviceNetWorkDidChangeNotification object:nil];
    [[TMSQLite shareInstance] connect:base];
    [self cacheImage];
    [self cacheTable];
}
+(void)textFieldBeginEditing:(NSNotification*)sender{
    UIView *textField = sender.object;
    if ([textField isKindOfClass:UIView.class]) {
        [TMGlobal setValue:textField forKey:@"focusObject"];
        //
        if ([textField window]) {
            static dispatch_once_t onceToken = 0;
            static UITapGestureRecognizer *instance = nil;
            dispatch_once(&onceToken, ^{
                instance = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
                [instance setCancelsTouchesInView:NO];
            });
            for (id gesture in textField.window.gestureRecognizers) {
                if (gesture == instance) {
                    return;
                }
            }
            [textField.window addGestureRecognizer:instance];
        }
    }else{
        [TMGlobal setValue:nil forKey:@"focusObject"];
    }
}
+(void)singleTap:(id)sender{
    UIView *focus = [TMGlobal valueForKey:@"focusObject"];
    if (focus) {
        [TMGlobal setValue:nil forKey:@"focusObject"];
        [focus resignFirstResponder];
    }
}
//
+(void)netWorkDidChange:(NSNotification*)sender{
    if ([TMGlobal valueForKey:@"user"] == nil) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self netWorkDidChange:sender];
        });
        return;
    }
    //
    [self cacheCommit];
}
//
+(id)totalToString:(id)price count:(id)count{
    if (price == nil || price == [NSNull null]) {
        return @"￥0.00";
    }
    if (count == nil || count == [NSNull null]) {
        return @"￥0.00";
    }
    return [NSString stringWithFormat:@"￥%0.2f", [price floatValue] * [count intValue]];
}
+(id)sizeToString:(id)size lable:(id)lable{
    if (lable == nil) {
        lable = @"";
    }
    if (size == nil || size == [NSNull null]) {
        return [NSString stringWithFormat:@"%@0mm", lable];
    }
    return [NSString stringWithFormat:@"%@%@mm", lable, size];
}
+(id)countToString:(id)count lable:(id)lable{
    if (lable == nil) {
        lable = @"x ";
    }
    if (count == nil || count == [NSNull null]) {
        return [NSString stringWithFormat:@"%@1",lable];
    }
    return [NSString stringWithFormat:@"%@%@",lable, count];
}
+(id)priceToString:(id)price lable:(id)lable{
    if (lable == nil) {
        lable = @"";
    }
    if (price == nil || price == [NSNull null]) {
        return [NSString stringWithFormat:@"%@￥0.00", lable];
    }
    return [NSString stringWithFormat:@"%@￥%0.2f", lable, [price floatValue]];
}
+(id)areaToString:(id)area lable:(id)lable{
    if (lable == nil) {
        lable = @"";
    }
    if (area == nil || area == [NSNull null]) {
        return [NSString stringWithFormat:@"%@0平米", lable];
    }
    return [NSString stringWithFormat:@"%@%d平米", lable, [area intValue]];
}
+(id)dateToString:(id)data lable:(id)lable{
    if (lable == nil) {
        lable = @"";
    }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[data integerValue]];
    return [NSString stringWithFormat:@"%@%@", lable, [date toString:@"yyyy-MM-dd"]];
}
+(id)objToString:(id)obj lable:(id)lable{
    if (lable == nil) {
        lable = @"";
    }
    if (obj == nil || obj == [NSNull null]) {
        return [NSString stringWithFormat:@"%@",lable];
    }
    if ([obj isKindOfClass:NSArray.class]) {
        NSString *str = [obj componentsJoinedByString:@","];
        return [NSString stringWithFormat:@"%@%@", lable, str];
    }
    if ([obj isKindOfClass:NSDictionary.class]) {
        NSString *str = @"";
        for (id key in [obj allKeys]) {
            id val = [obj objectForKey:key];
            if (val) {
                str = [str stringByAppendingFormat:@"%@:%@", key, val];
            }
        }
        return [NSString stringWithFormat:@"%@%@", lable, str];
    }
    return [NSString stringWithFormat:@"%@%@", lable, obj];
}
//
+(id)getPath:(id)path{
    NSString *app = [AppDataRoot stringByAppendingPathComponent:[path stringByReplacingOccurrencesOfString:@"./" withString:@""]];
    return [app stringByReplacingOccurrencesOfString:@":/" withString:@"://"];
}
+(id)loadImage:(id)image view:(UIImageView*)view{
    if ([view isKindOfClass:UIImageView.class]) {
        if ([image isKindOfClass:NSString.class]) {
            [view load:image base:AppDataRoot];
        }else{
            [view setImage:nil];
        }
        return view;
    }
    return nil;
}
+(id)loadJson:(NSString*)api key:(NSString*)key data:(id)data{
    return [self loadJson:api key:key data:data commit:YES];
}
+(id)loadJson:(NSString*)api key:(NSString*)key data:(id)data commit:(BOOL)commit{
    id user = [TMGlobal valueForKey:@"user"];
    if (user) {
        if ([api rangeOfString:@"?"].location != NSNotFound) {
            api = [api stringByAppendingFormat:@"&token=%@", [user objectForKey:@"token"]];
        }else{
            api = [api stringByAppendingFormat:@"?token=%@", [user objectForKey:@"token"]];
        }
        //
        if (commit == YES) {
            [self cacheCommit];
        }
    }
    //
    api = [api stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:[AppDataRoot stringByAppendingString:api]];
    TMLoader *loader = [TMLoader load:[TMRequest requestWithURL:url data:data] delegate:nil cache:0];
    if (loader) {
        NSString *json = [[NSString alloc] initWithData:loader.data encoding:NSUTF8StringEncoding];
        id temp = [TMJSON parse:json];
        if ([temp isKindOfClass:NSDictionary.class]) {
            id code = [[temp objectForKey:@"meta"] objectForKey:@"code"];
            if (code == nil || (code && [code intValue] == 200)) {
                if (key != nil) {
                    id obj = [temp objectForKey:key];
                    if (obj == [NSNull null]) {
                        return nil;
                    }
                    return obj;
                }
                return temp;
            }else{
                if (code && [code intValue] == 400) {
                    UINavigationController *root = (id)[[[UIApplication sharedApplication] keyWindow] rootViewController];
                    [root dismissViewControllerAnimated:YES completion:nil];
                    if ([root isKindOfClass:UINavigationController.class]) {
                        [root popToRootViewControllerAnimated:YES];
                    }
                    return nil;
                }
            }
            return nil;
        }
        return temp;
    }
    return nil;
}
//数据库操作
+(id)fromFields:(NSString*)from{
    static NSMutableDictionary *instance = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        instance = [[NSMutableDictionary alloc] init];
    });
    //
    if (from) {
        NSMutableSet *fields = [instance objectForKey:from];
        if (fields == nil) {
            fields = [NSMutableSet set];
            NSArray *items = [[TMSQLite shareInstance] query:[NSString stringWithFormat:@"PRAGMA table_info(%@)", from]];
            for (id item in items) {
                id name = [item objectForKey:@"name"];
                if (name) {
                    [fields addObject:name];
                }
            }
            [instance setValue:fields forKey:from];
        }
        return fields;
    }
    return nil;
}
+(id)fromInsert:(NSString*)from data:(NSDictionary*)data{
    NSMutableSet *fields = [self fromFields:from];
    if (fields && [fields count] > 0) {
        NSMutableArray *keys = [NSMutableArray array];
        NSMutableArray *vals = [NSMutableArray array];
        for (id key in [fields objectEnumerator]) {
            id value = [data valueForKey:key];
            if (value && [NSNull null] != value) {
                if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]){
                    id temp = [value duplicate];
                    value = [TMJSON stringify:temp];
                }
                if(value){
                    if ([value isKindOfClass:[NSString class]]) {
                        NSString *str = [value stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
                        [vals addObject:[NSString stringWithFormat:@"'%@'",str]];
                    }else{
                        [vals addObject:value];
                    }
                    [keys addObject:[NSString stringWithFormat:@"'%@'",key]];
                }
            }
        }
        if (keys.count == vals.count && keys.count > 0) {
            id key = [keys componentsJoinedByString:@","];
            id value = [vals componentsJoinedByString:@","];
            return [NSString stringWithFormat:@"REPLACE INTO %@ (%@) VALUES (%@)", from, key, value];
        }
    }
    return nil;
}
+(id)fromDelete:(NSString*)from value:(id)value {
    NSMutableSet *fields = [self fromFields:from];
    if (fields && [fields count] > 0) {
        if (value && [fields containsObject:@"uuid"]) {
            NSMutableArray *uuid = [NSMutableArray array];
            if ([value isKindOfClass:NSArray.class]) {
                for (id item in value) {
                    if ([item isKindOfClass:NSDictionary.class]) {
                        id uid = [item objectForKey:@"uuid"];
                        if (uid && uid != [NSNull null]) {
                            [uuid addObject:[NSString stringWithFormat:@"'%@'" ,uid]];
                        }
                    }
                }
            }
            if ([value isKindOfClass:NSDictionary.class]) {
                id uid = [value objectForKey:@"uuid"];
                if (uid && uid != [NSNull null]) {
                    [uuid addObject:[NSString stringWithFormat:@"'%@'" ,uid]];
                }
            }
            if ([uuid count] > 0) {
                NSString *temp = [uuid componentsJoinedByString:@","];
                if ([fields containsObject:@"delete"]) {
                    return [NSString stringWithFormat:@"DELETE FROM %@ WHERE uuid IN (%@) OR delete=1", from, temp];
                }
                return [NSString stringWithFormat:@"DELETE FROM %@ WHERE uuid IN (%@)", from, temp];
            }
        }
        //
        if ([fields containsObject:@"delete"]) {
            return [NSString stringWithFormat:@"DELETE FROM %@ WHERE delete=1", from];
        }
    }
    return nil;
}
//缓存
+(NSString*)cacheImage{
    static BOOL hasTable = NO;
    static NSString *tableName = @"cache_image";
    if (hasTable == NO) {
        NSString *sql = [NSString stringWithFormat:@"PRAGMA table_info(\"%@\")", tableName];
        if ([[TMSQLite shareInstance] query:sql] == nil) {
            sql = [NSString stringWithFormat:@"CREATE TABLE %@ ('id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,'path' text)",tableName];
            [[TMSQLite shareInstance] query:sql];
        }
        hasTable = YES;
    }
    return tableName;
}
+(id)cacheImage:(UIImage*)image path:(NSString*)path{
    if ([image isKindOfClass:UIImage.class]) {
        if (path == nil) {
            path = [NSString stringWithFormat:@"data/myfile/%@.png",[NSString uuid]];
        }
        NSData *byte = nil;
        if ([[[path pathExtension] lowercaseString] isEqualToString:@"jpg"]) {
            byte = UIImageJPEGRepresentation(image, 1);
        }
        if ([[[path pathExtension] lowercaseString] isEqualToString:@"png"]) {
            byte = UIImagePNGRepresentation(image);
        }
        //
        if (byte) {
            NSString *file = [NSString libraryAppend:path];
            NSString *temp = [file stringByDeletingLastPathComponent];
            if ([[NSFileManager defaultManager] fileExistsAtPath:temp] == NO) {
                [[NSFileManager defaultManager] createDirectoryAtPath:temp withIntermediateDirectories:YES attributes:nil error:nil];
            }
            if ([byte writeToFile:file atomically:YES]) {
                if ([[UIDevice currentDevice] network] == UIDeviceNetworkNone) {
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    [dic setValue:path forKey:@"path"];
                    //
                    NSString *sql = [self fromInsert:[self cacheImage] data:dic];
                    [[TMSQLite shareInstance] query:sql];
                }
                return path;
            }
        }
    }
    return nil;
}
//type[0:删除，1:更新]
+(NSString*)cacheTable{
    static BOOL hasTable = NO;
    static NSString *tableName = @"cache_table";
    if (hasTable == NO) {
        NSString *sql = [NSString stringWithFormat:@"PRAGMA table_info(\"%@\")", tableName];
        if ([[TMSQLite shareInstance] query:sql] == nil) {
            sql = [NSString stringWithFormat:@"CREATE TABLE %@ ('id' integer NOT NULL PRIMARY KEY AUTOINCREMENT,'key' text,'value' text,'table' text,'type' integer)",tableName];
            [[TMSQLite shareInstance] query:sql];
        }
        hasTable = YES;
    }
    return tableName;
}
+(BOOL)cacheData:(id)data table:(NSString*)table key:(NSString*)key type:(NSInteger)type{
    NSMutableArray *temps = [NSMutableArray array];
    if ([data isKindOfClass:NSArray.class]) {
        for (id item in data) {
            if ([item isKindOfClass:NSDictionary.class]) {
                [temps addObject:item];
            }
        }
    }
    if ([data isKindOfClass:NSDictionary.class]) {
        [temps addObject:data];
    }
    //
    if([temps count] > 0){
        //清除无效&重复
        NSString *sql = [self fromDelete:table value:temps];
        [[TMSQLite shareInstance] query:sql];
        //
        if (type > 0) {
            for (id item in temps) {
                if ([item isKindOfClass:NSDictionary.class]) {
                    id value = [item objectForKey:key];
                    if (value && [value isKindOfClass:NSString.class]) {
                        sql = [self fromInsert:table data:item];
                        if ([[TMSQLite shareInstance] query:sql]) {
                            if ([item objectForKey:@"id"] == nil) {
                                int rowId = [[TMSQLite shareInstance] rowId];
                                [item setValue:[NSNumber numberWithInt:rowId] forKey:@"id"];
                            }
                        }
                    }
                }
            }
        }
        //
        if ([[UIDevice currentDevice] network] == UIDeviceNetworkNone) {
            for (id item in temps) {
                if ([item isKindOfClass:NSDictionary.class]) {
                    id value = [item objectForKey:key];
                    if (value && [value isKindOfClass:NSString.class]) {
                        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                        [dic setValue:[NSNumber numberWithInteger:type] forKey:@"type"];
                        [dic setValue:table forKey:@"table"];
                        [dic setValue:value forKey:@"value"];
                        [dic setValue:key forKey:@"key"];
                        //
                        NSString *sql = [self fromInsert:[self cacheTable] data:dic];
                        [[TMSQLite shareInstance] query:sql];
                    }
                }
            }
            return YES;
        }
    }
    return NO;
}
+(BOOL)cacheCommit{
    if ([TMGlobal valueForKey:@"user"] && [[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        //上传图片
        NSString *image = [self cacheTable];
        NSArray *images = [[TMSQLite shareInstance] query:[NSString stringWithFormat:@"SELECT * FROM %@", image]];
        for (id item in images) {
            NSString *path = [item objectForKey:@"path"];
            NSString *file = [NSString libraryAppend:path];
            NSData *image = [NSData dataWithContentsOfFile:file];
            if (image) {
                NSMutableDictionary *post = [NSMutableDictionary dictionary];
                [post setValue:[image base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed] forKey:@"picdata"];
                [post setValue:[path pathExtension] forKey:@"extname"];
                [post setValue:path forKey:@"path"];
                //
                if ([self loadJson:@"?n=api&a=user&c=other&m=save_pic" key:nil data:post commit:NO]) {
                    [[TMSQLite shareInstance] query:[NSString stringWithFormat:@"DELETE FROM %@ WHERE id=%@", image, [item objectForKey:@"id"]]];
                    [NSThread sleepForTimeInterval:0.1];
                }
            }
        }
        //上传数据
        NSString *table = [self cacheTable];
        NSArray *tables = [[TMSQLite shareInstance] query:[NSString stringWithFormat:@"SELECT * FROM %@", table]];
        if (tables) {
            NSMutableArray *delete = [NSMutableArray array];
            NSMutableArray *update = [NSMutableArray array];
            for (id item in tables) {
                if ([[item objectForKey:@"type"] intValue]==1) {
                    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@='%@'", [item objectForKey:@"table"], [item objectForKey:@"key"], [item objectForKey:@"value"]];
                    NSMutableDictionary *value = [[[TMSQLite shareInstance] query:sql] lastObject];
                    if (value && [value isKindOfClass:NSDictionary.class]) {
                        NSMutableDictionary *copy = [NSMutableDictionary dictionary];
                        for (id k in value.allKeys) {
                            if (NO == [k isEqual:@"id"]) {
                                id v = [value objectForKey:k];
                                if (v != [NSNull null]) {
                                    [copy setValue:v forKey:k];
                                }
                            }
                        }
                        //
                        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
                        [temp setValue:[item objectForKey:@"table"] forKey:@"table"];
                        [temp setValue:copy forKey:@"data"];
                        [update addObject:temp];
                    }
                }else{
                    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
                    [temp setValue:[item objectForKey:@"table"] forKey:@"table"];
                    [temp setValue:[item objectForKey:@"value"] forKey:@"value"];
                    [temp setValue:[item objectForKey:@"key"] forKey:@"key"];
                    [delete addObject:temp];
                }
            }
            //上传
            if (update.count > 0) {
                NSMutableDictionary *data = [NSMutableDictionary dictionary];
                [data setValue:[TMJSON stringify:update] forKey:@"items"];
                //
                if ([self loadJson:@"?n=api&a=user&c=other&m=general_update" key:nil data:data commit:NO]) {
                    [[TMSQLite shareInstance] query:[NSString stringWithFormat:@"DELETE FROM %@ WHERE type=1",table]];
                }
            }
            if (delete.count > 0) {
                NSMutableDictionary *data = [NSMutableDictionary dictionary];
                [data setValue:[TMJSON stringify:delete] forKey:@"items"];
                //
                if ([self loadJson:@"?n=api&a=user&c=other&m=general_del" key:nil data:data commit:NO]) {
                    [[TMSQLite shareInstance] query:[NSString stringWithFormat:@"DELETE FROM %@ WHERE type!=1",table]];
                }
            }
        }
        return YES;
    }
    return NO;
}
//
//
//
//
+(id)getAllChildId:(NSArray*)data parentid:(id)parentid{
    if (parentid) {
        NSMutableArray *array = [NSMutableArray arrayWithObject:parentid];
        [array addObject:parentid];
        //
        for (id v in data) {
            if ([[v objectForKey:@"parentid"] isEqual:parentid]) {
                id cid = [v objectForKey:@"id"];
                if (cid) {
                    [array addObject:cid];
                    //
                    NSArray *ids = [self getAllChildId:data parentid:cid];
                    if (ids) {
                        [array addObjectsFromArray:ids];
                    }
                }
            }
        }
        return array;
    }
    return nil;
}
+(id)userLogin:(NSDictionary*)user{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSString *sql = @"DELETE FROM e360_user WHERE parentid=0 OR parentid isNull";
        [[TMSQLite shareInstance] query:sql];
        //
        id dic = [self loadJson:@"?n=api&a=login&c=user" key:nil data:user commit:NO];
        if ([dic isKindOfClass:NSDictionary.class]) {
            id company = [dic objectForKey:@"company"];
            sql = [self fromInsert:@"e360_company" data:company];
            [[TMSQLite shareInstance] query:sql];
            //
            id user = [dic objectForKey:@"user"];
            sql = [self fromInsert:@"e360_user" data:user];
            [[TMSQLite shareInstance] query:sql];
        }else{
            return [NSError errorWithDomain:NSCocoaErrorDomain code:400 userInfo:@{@"message":@"用户名或密码错误!"}];
        }
    }
    //
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM e360_user WHERE username='%@' AND password='%@' AND (parentid=0 OR parentid isNull)",[user objectForKey:@"username"],[[user objectForKey:@"password"] md5]];
    NSMutableDictionary *data = [[[TMSQLite shareInstance] query:sql] firstObject];
    if (data == nil) {
        return [NSError errorWithDomain:NSCocoaErrorDomain code:400 userInfo:@{@"message":@"请检查网络连接!"}];
    }
    sql = [NSString stringWithFormat:@"SELECT * FROM e360_company WHERE id=%@", [data objectForKey:@"companyid"]];
    [data setValue:[[[TMSQLite shareInstance] query:sql] firstObject] forKey:@"company"];
    return data;
}
+(id)ideaEdit:(NSDictionary*)idea{
    if (NO == [self cacheData:idea table:@"e360_idea" key:@"uuid" type:1]) {
        NSMutableDictionary *item = [NSMutableDictionary dictionary];
        [item setValue:[idea objectForKey:@"content"] forKey:@"content"];
        [item setValue:[idea objectForKey:@"title"] forKey:@"title"];
        [item setValue:[idea objectForKey:@"tag"] forKey:@"tag"];
        //
        NSMutableArray *items = [NSMutableArray array];
        [items addObject:item];
        //
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setValue:[TMJSON stringify:items] forKey:@"items"];
        //
        id dic = [self loadJson:@"?n=api&a=datas&c=other&m=ideainsert" key:nil data:data];
        if (dic) {
            return idea;
        }else{
            return nil;
        }
    }
    return idea;
}
+(id)areaList:(id)pid{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM e360_area WHERE parentid=%@", pid];
    return [[TMSQLite shareInstance] query:sql];
}
@end
